package com.css.zfzx.sjcj.modules.hddcActiveFaultPositionerror.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcActiveFaultPositionerror.repository.HddcActivefaultpositionerrorNativeRepository;
import com.css.zfzx.sjcj.modules.hddcActiveFaultPositionerror.repository.HddcActivefaultpositionerrorRepository;
import com.css.zfzx.sjcj.modules.hddcActiveFaultPositionerror.repository.entity.HddcActivefaultpositionerrorEntity;
import com.css.zfzx.sjcj.modules.hddcActiveFaultPositionerror.viewobjects.HddcActivefaultpositionerrorQueryParams;
import com.css.zfzx.sjcj.modules.hddcActiveFaultPositionerror.viewobjects.HddcActivefaultpositionerrorVO;
import com.css.zfzx.sjcj.modules.hddcActiveFaultPositionerror.service.HddcActivefaultpositionerrorService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcActivefaultpositionerrorServiceImpl implements HddcActivefaultpositionerrorService {

	@Autowired
    private HddcActivefaultpositionerrorRepository hddcActivefaultpositionerrorRepository;
    @Autowired
    private HddcActivefaultpositionerrorNativeRepository hddcActivefaultpositionerrorNativeRepository;

    @Override
    public JSONObject queryHddcActivefaults(HddcActivefaultpositionerrorQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcActivefaultpositionerrorEntity> hddcActivefaultPage = this.hddcActivefaultpositionerrorNativeRepository.queryHddcActivefaults(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcActivefaultPage);
        return jsonObject;
    }


    @Override
    public HddcActivefaultpositionerrorEntity getHddcActivefault(String id) {
        HddcActivefaultpositionerrorEntity hddcActivefault = this.hddcActivefaultpositionerrorRepository.findById(id).orElse(null);
         return hddcActivefault;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcActivefaultpositionerrorEntity saveHddcActivefault(HddcActivefaultpositionerrorEntity hddcActivefault) {
        String uuid = UUIDGenerator.getUUID();
        hddcActivefault.setUuid(uuid);
        hddcActivefault.setCreateUser(PlatformSessionUtils.getUserId());
        hddcActivefault.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcActivefault.setIsValid("1");
        hddcActivefault.setQualityinspectionStatus("0");
        hddcActivefault.setExtends10("1");
        this.hddcActivefaultpositionerrorRepository.save(hddcActivefault);
        return hddcActivefault;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcActivefaultpositionerrorEntity> saveHddcActivefaultList(List<HddcActivefaultpositionerrorEntity> list) {
        for (HddcActivefaultpositionerrorEntity hddcActivefault : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcActivefault.setUuid(uuid);
            hddcActivefault.setCreateUser(PlatformSessionUtils.getUserId());
            hddcActivefault.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcActivefault.setIsValid("1");
            hddcActivefault.setQualityinspectionStatus("0");
            hddcActivefault.setExtends10("1");
        }
        Iterable<HddcActivefaultpositionerrorEntity> iterable = hddcActivefaultpositionerrorNativeRepository.batchSave(list);
        return iterable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcActivefaultpositionerrorEntity updateHddcActivefault(HddcActivefaultpositionerrorEntity hddcActivefault) {
        HddcActivefaultpositionerrorEntity entity = hddcActivefaultpositionerrorRepository.findById(hddcActivefault.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcActivefault);
        hddcActivefault.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcActivefault.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcActivefaultpositionerrorRepository.save(hddcActivefault);
        return hddcActivefault;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcActivefaults(List<String> ids) {
        List<HddcActivefaultpositionerrorEntity> hddcActivefaultList = this.hddcActivefaultpositionerrorRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcActivefaultList) && hddcActivefaultList.size() > 0) {
            for(HddcActivefaultpositionerrorEntity hddcActivefault : hddcActivefaultList) {
//                this.hddcActivefaultRepository.delete(hddcActivefault);
                hddcActivefault.setIsValid("0");
                hddcActivefault.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcActivefault.setUpdateTime(new Date());
                this.hddcActivefaultpositionerrorRepository.save(hddcActivefault);

            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcActivefaultpositionerrorQueryParams queryParams, HttpServletResponse response) {
        List<HddcActivefaultpositionerrorEntity> yhDisasterEntities = hddcActivefaultpositionerrorNativeRepository.exportYhDisasters(queryParams);
        List<HddcActivefaultpositionerrorVO> list=new ArrayList<>();
        for (HddcActivefaultpositionerrorEntity entity:yhDisasterEntities) {
            HddcActivefaultpositionerrorVO yhDisasterVO=new HddcActivefaultpositionerrorVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "活断层位置误差", "活断层位置误差", HddcActivefaultpositionerrorVO.class, "活断层位置误差.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcActivefaultpositionerrorVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcActivefaultpositionerrorVO.class, params);
            List<HddcActivefaultpositionerrorVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcActivefaultpositionerrorVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcActivefaultpositionerrorVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    public void saveDisasterList( List<HddcActivefaultpositionerrorVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcActivefaultpositionerrorEntity yhDisasterEntity = new HddcActivefaultpositionerrorEntity();
            HddcActivefaultpositionerrorVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcActivefault(yhDisasterEntity);
        }
    }


    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcActivefaultpositionerrorEntity> hddcA1InvrgnhasmaterialtableList = this.hddcActivefaultpositionerrorRepository.queryByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcActivefaultpositionerrorEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcActivefaultpositionerrorRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcActivefaultpositionerrorEntity> hddcA1InvrgnhasmaterialtableList = this.hddcActivefaultpositionerrorRepository.queryByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcActivefaultpositionerrorEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcActivefaultpositionerrorRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }

    @Override
    public List<HddcActivefaultpositionerrorEntity> findAll() {
        List<HddcActivefaultpositionerrorEntity> list=this.hddcActivefaultpositionerrorRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        String uuser = PlatformSessionUtils.getUserId();
        Date deletedate=PlatformDateUtils.getCurrentTimestamp();
        hddcActivefaultpositionerrorRepository.deleteFileData(provinceName,cityName,areaName,savefilename,uuser,deletedate);
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("Scale")){
            str+="Scale,";
        }
        if(!set.contains("FractureZoneName")){
            str+="FractureZoneName,";
        }
        if(!set.contains("Name")){
            str+="Name,";
        }
        if(!set.contains("FaultSegmentName")){
            str+="FaultSegmentName,";
        }
        if(!set.contains("StrikeDirection")){
            str+="StrikeDirection,";
        }
        if(!set.contains("Strike")){
            str+="Strike,";
        }
        if(!set.contains("Direction")){
            str+="Direction,";
        }
        if(!set.contains("Clination")){
            str+="Clination,";
        }
        if(!set.contains("Length")){
            str+="Length,";
        }
        if(!set.contains("TopDepth")){
            str+="TopDepth,";
        }
        if(!set.contains("Width")){
            str+="Width,";
        }
        if(!set.contains("FractureBeltWidth")){
            str+="FractureBeltWidth,";
        }
        if(!set.contains("Feature")){
            str+="Feature,";
        }
        if(!set.contains("LatestActivePeriod")){
            str+="LatestActivePeriod,";
        }
        if(!set.contains("StartTimeEst")){
            str+="StartTimeEst,";
        }
        if(!set.contains("VDisplaceEst")){
            str+="VDisplaceEst,";
        }
        if(!set.contains("VDisplaceEr")){
            str+="VDisplaceEr,";
        }
        if(!set.contains("HDisplaceEst")){
            str+="HDisplaceEst,";
        }
        if(!set.contains("TDisplaceEst")){
            str+="TDisplaceEst,";
        }
        if(!set.contains("TDisplaceEr")){
            str+="TDisplaceEr,";
        }
        if(!set.contains("AveVRate")){
            str+="AveVRate,";
        }
        if(!set.contains("AveVRateEr")){
            str+="AveVRateEr,";
        }
        if(!set.contains("AveHRate")){
            str+="AveHRate,";
        }
        if(!set.contains("AveHRateEr")){
            str+="AveHRateEr,";
        }
        if(!set.contains("StartTimeNewest")){
            str+="StartTimeNewest,";
        }
        if(!set.contains("NewVRate")){
            str+="NewVRate,";
        }
        if(!set.contains("NewVRateEr")){
            str+="NewVRateEr,";
        }
        if(!set.contains("NewHRate")){
            str+="NewHRate,";
        }
        if(!set.contains("NewHRateEr")){
            str+="NewHRateEr,";
        }
        if(!set.contains("MaxVRate")){
            str+="MaxVRate,";
        }
        if(!set.contains("MaxVRateEr")){
            str+="MaxVRateEr,";
        }
        if(!set.contains("MaxHRate")){
            str+="MaxHRate,";
        }
        if(!set.contains("MaxHRateEr")){
            str+="MaxHRateEr,";
        }
        if(!set.contains("EQEventCount")){
            str+="EQEventCount,";
        }
        if(!set.contains("EQEventRIBottom")){
            str+="EQEventRIBottom,";
        }
        if(!set.contains("EQEventRITop")){
            str+="EQEventRITop,";
        }
        if(!set.contains("Method")){
            str+="Method,";
        }
        if(!set.contains("MaxRuptureLength")){
            str+="MaxRuptureLength,";
        }
        if(!set.contains("AverageRuptureLength")){
            str+="AverageRuptureLength,";
        }
        if(!set.contains("ElapseTimeForLatestEQ")){
            str+="ElapseTimeForLatestEQ,";
        }
        if(!set.contains("SlipDepthEst")){
            str+="SlipDepthEst,";
        }
        if(!set.contains("SlipDepthEr")){
            str+="SlipDepthEr,";
        }
        if(!set.contains("AverageSlipRateEst")){
            str+="AverageSlipRateEst,";
        }
        if(!set.contains("AverageSlipRateEr")){
            str+="AverageSlipRateEr,";
        }
        if(!set.contains("CreepRateEst")){
            str+="CreepRateEst,";
        }
        if(!set.contains("CreepRateEr")){
            str+="CreepRateEr,";
        }
        if(!set.contains("CoSeismicMaxSlipEst")){
            str+="CoSeismicMaxSlipEst,";
        }
        if(!set.contains("CoSeismicMaxSlipEr")){
            str+="CoSeismicMaxSlipEr,";
        }
        if(!set.contains("CoSeismicAverageSlipEst")){
            str+="CoSeismicAverageSlipEst,";
        }
        if(!set.contains("CoSeismicAverageSlipEr")){
            str+="CoSeismicAverageSlipEr,";
        }
        if(!set.contains("LatestCoSeismicSlipEst")){
            str+="LatestCoSeismicSlipEst,";
        }
        if(!set.contains("LatestCoSeismicSlipEr")){
            str+="LatestCoSeismicSlipEr,";
        }
        if(!set.contains("nsb1")){
            str+="nsb1,";
        }
        if(!set.contains("nsb2")){
            str+="nsb2,";
        }
        if(!set.contains("nsb3")){
            str+="nsb3,";
        }
        if(!set.contains("ShowCode")){
            str+="ShowCode,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    private String getStrBySourceStr(String source){
        if(StringUtils.isEmpty(source)){
            return "0";
        }
         return source;
    }


    public void savehddcActivefaultpositionerrorServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            Integer count11=this.hddcActivefaultpositionerrorRepository.getCountByArea(provinceName,cityName,areaName);
            if(count11>0){
                throw new RuntimeException("当前区县已有断层误差数据，请先删除数据再进行导入。");
            }
            List<HddcActivefaultpositionerrorEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcActivefaultpositionerrorEntity data = new HddcActivefaultpositionerrorEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                String code=obs.get(1).toString();
                String name=obs.get(2).toString();
                Integer count=this.hddcActivefaultpositionerrorRepository.getCountByAreaAndIdAndName(provinceName,cityName,areaName,code,name);
                if(count==0){
                    throw new RuntimeException("当前区县没有相对应的活断层数据，编号为："+code+" 名称为："+name);
                }
                data.setId(code);
                data.setName(name);
                String pstr=obs.get(0).toString();
                data.setExtends15(pstr);
                data.setExtends16("CGCS2000");
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
            }
            //deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcActivefaultList(datas);
        }
    }

    public void deleteByCreateUser(String provinceName, String cityName, String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcActivefaultpositionerrorEntity> hddcActivefaultList = this.hddcActivefaultpositionerrorRepository.queryHddcActivefaultsByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcActivefaultList) && hddcActivefaultList.size() > 0) {
            hddcActivefaultpositionerrorRepository.deleteAll(hddcActivefaultList);
        }
    }

}
